/**
 * Created by dylan_Apple on 17/6/25.
 */
var async = require('async');
var stockRecommend = require('../controller/controller.stockrecommend');
var stockChannelDAO = require('../controller/controller.stockChannel');
var stockpoolDAO = require('../controller/controller.stockpoolgroup');
var user = require('../controller/controller.user');
var dicStock = require('../controller/controller.dic-stock');
var comment = require('../controller/controller.comment');
var Excel = require('../utils/excel.js');
var wx = require('../utils/wx');
var fileUtil = require('../utils/fileUtil')('disk');
var aliOSS = require('../utils/ali-oss');
var stockUtil = require('../utils/stock');
module.exports = {

    //初始化个股推荐
    initStockRecommend: function (req, res, next) {
        var that = this;
        async.parallel({
            person: function (callback) {
                user.getUserList({}, function (err, result) {
                    if (err) {
                        handleError(res, err);
                    } else {
                        callback(null, result);
                    }
                })
            },
            info:function (callback) {
                if(req.query.rowId){
                    that.getStockRecommendInfo(req, res, function (result) {
                        callback(null,result);
                    });
                }else{
                    callback(null, {});
                }
            }
        }, function (err, results) {
            if (err) {
                handleError(res, err);
            } else {
                next(results);
            }
        })
    },

    //创建或更新股票池
    createOrUpdateStockPool: function (req, res, next) {
        var createUid = req.session.uid;
        fileUtil.uploadSingleFile(req, res, 'file',function (err, fields, file) {
            fields.createUid = createUid;
            fields.actionType = "stockrecommend";
            fields.isRecommend='0';

            var stockChannel = {};//在stockChannel表也创建一条记录
            stockChannel.stockId = fields.stockId;
            stockChannel.channelType = 'stockEstimate';
            stockChannel.createUid = createUid;
            stockChannel.enable = '1';
            stockChannel.level = '暂无';
            stockChannel.industry = '565b23e2-dc01-495c-9402-1608d154318';

            if (err){
                next(err);
                return;
            }else{
                var daoMethod = stockRecommend[fields.rowId?'update':'create'];
                var addStockChannel = fields.rowId?0:1;
                if(file){
                    fields.attachmentName = fields.attachmentName || file.originalname;
                    var userinfo = req.session && req.session.userinfo;
                    var filename = [(userinfo && userinfo.name) || file.fieldname, Date.now(), file.originalname].join('-');
                    aliOSS.upload(filename,fileUtil.getFileAsStream(file.path))
                        .then(function (result) {
                            fileUtil.deleteFileFromDisk(file.path);
                            fields.attachmentUrl = result.url;
                            daoMethod(fields, function (err, result) {
                                if(addStockChannel == 1){
                                    stockChannelDAO.create(stockChannel, function (err, res) {
                                        next(err || result);
                                    })
                                }

                            });
                        }).catch(function (err) {
                            fileUtil.deleteFileFromDisk(file.path);
                            console.error(err);
                            next({code:500,msg:'form save failed.'});
                    });
                }else{
                    daoMethod(fields, function (err, result) {
                        if(addStockChannel == 1){
                            stockChannelDAO.create(stockChannel, function (err, res) {
                                next(err || result);
                            })
                        }
                    });
                }
            }
        });
    },
    //获取股票池详情
    getStockRecommendInfo: function (req, res, next) {
        var params = req.query;
        async.parallel({
            commentList:function(done){
                params.type = 'stockpool';
                comment.getListByMconference(params, function (err, result) {
                    done(err,result && result.obj);
                });
            },
            mConference:function(done){
                stockRecommend.getInfo(params, function (err, result) {
                    if (err) {
                        res.redirect('/error');
                        return;
                    }
                    done(err, result && result.obj);
                });
            }
        },function(error,results){
            next(results);
        });
    },
    //获取个股推荐列表
    getStockRecommendList: function (req, res, next) {
        var params = req.query;
        params.actionType="stockrecommend";
        params.enable='1';
        stockRecommend.getListByActionType(params, function (err, result) {
            if (err) {
                res.redirect('/error');
                return;
            }
            next({
                    'mconferencelist': result.obj,
                    moment: require("moment")
                }
            );
        });
    },
    //获取带股票池分组信息的个股推荐列表
    getStockRecommendListWithGroup:function(req,res,next){
        var that = this;
        async.parallel({
            stockpoolGroup:function(done){
                that.listStockPoolGroup(req,res,function(result){
                    if(result.obj)
                        done(null,result.obj);
                    else
                        done(result,null);
                });
            },
            stockRecommendList:function(done){
                req.query.isRecommend = "0";
                that.getStockRecommendList(req,res,function(result){
                     done(null, result);
                });
            }
        },function(error,result){
            if(!error){
                var stockCodes = [];
                var list = result&&result.stockRecommendList&&result.stockRecommendList.mconferencelist||[];
                for(stock of list){
                    stockCodes.push(stock.stockId && stock.stockId.stockCode || "");
                }
                stockUtil.getRealtimeListPrice(stockCodes,function (err,res) {
                    next(createStockPoolTree(result.stockpoolGroup, result.stockRecommendList,res));
                });


            }
            else{
                console.error(error);
                res.redirect('/error');
                return;
            }
        });

        function createStockPoolTree(stockpoolGroup, stockRecommendListObj,prices) {
            var stockRecommendList = stockRecommendListObj.mconferencelist;
            var tree = stockpoolGroup,rootRecommendList = [],i;
            var flatMap = {};
            for (i=0;i<stockpoolGroup.length;i++){//初始化flatMap
                var j;
                var parent = stockpoolGroup[i];
                var key = parent.id;
                parent.list = [];
                flatMap[key] = parent;

                var children = parent.children || [];
                for (j = 0;j<children.length;j++){
                   var child = children[j];
                   var key = child.id;
                   child.list = [];
                   flatMap[key] = child;
                }
            }

            for (i=0;i<stockRecommendList.length;i++){//为flatMap赋值
                stockRecommendList[i].realPrice = prices[i];
                var stock = stockRecommendList[i];
                var parentPoolId = stock.parentPoolId;
                var childPoolId = stock.childPoolId;
                if (childPoolId && flatMap[childPoolId]){
                    flatMap[childPoolId].list.push(stock);
                    flatMap[parentPoolId].count = (flatMap[parentPoolId].count || 0)+1;
                }else if (parentPoolId && flatMap[parentPoolId]){
                    flatMap[parentPoolId].list.push(stock);
                }else{
                    rootRecommendList.push(stock);
                }
            }

            for (i=0;i<tree.length;i++){//整理tree
                var j,parentCount;
                var parent = tree[i];
                var key = parent.id;
                parentCount = parent.list.length;
                var children = parent.children || [];
                for (j = 0;j<children.length;j++){
                    var child = children[j];
                    var key = child.id;
                    child.count = flatMap[key].list.length;
                    parentCount += child.count;
                }
                parent.count = parentCount;
                parentCount=0;
            }

            return {mconferencelist:stockRecommendListObj.mconferencelist,tree:tree, other:rootRecommendList,moment:stockRecommendListObj.moment};
        }
    },
    //导出个股推荐列表Excel
    exportStockPoolAsExcel:function (req, res, next) {
        var columns = [
            { header: '股票名称', key: 'stockName', width: 20 },
            { header: '调入价', key: 'importPrice', width: 10 },
            { header: '目标价', key: 'expectPrice', width: 10 },
            { header: '目标盈利率', key: 'expectRate', width: 10 },
            { header: '实际盈利率', key: 'realRate', width: 10 },
            { header: '分析师', key: 'createUserName', width: 10 }
        ];

        var handler =  function (excel) {
            res.type('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            res.attachment(encodeURI('股票池.xlsx'));
            excel.writeStream(res, function () {
                res.end();
            });
         }

        this.getStockRecommendList(req, res,function (result) {
            var rows = [];
            var mconferencelist = result.mconferencelist;
            for (var i=0;i<mconferencelist.length;i++){
                var stock = mconferencelist[i];
                var row = {stockName:stock.stockId.name,importPrice:stock.importPrice,
                    expectPrice:stock.expectPrice,expectRate:stock.expectRate,
                    realRate:stock.realRate,createUserName:stock.createUserId&&stock.createUserId.name
                };
                rows.push(row);
            }
            var excel = new Excel();
            excel.createSheet('Sheet1',columns,rows);
            handler(excel);
        });
    },
    //删除股票池
    delteStockRecommendList: function (req, res, next) {
        var params = req.body;
        async.waterfall([
            function (done) {
                stockRecommend.getInfo(params, function (err, result) {
                    if (err) {
                        next({'code': 404, 'message': "调出错误"});
                        return;
                    }
                    done(err, result && result.obj);
                });
            },
            function (stockInfo, done) {
                stockUtil.getRealRate(stockInfo.importPrice,stockInfo.stockId.stockCode,function (err, realRate) {
                    done(err, realRate);
                });
            },
            function (realRate,done) {
                params.realRate = realRate;
                stockRecommend.deleteStockRecommend(params, function (err, result) {
                    done(err, result);
                });
            }
        ], function (error, result) {
            if (error){
                console.log(error);
                next({code: 404, message: '调出错误'})
            }else{
                console.log(result);
                next({code: 200, message: '调出成功'});
            }
        });
    },

    //新建股票池分组
    createStockPoolGroup:function(req, res, next){
        var params = req.body;
        if (params == null) {
            res.redirect('/error');
            return;
        }
        stockpoolDAO.create(params,function(err,result){
            next(err || result);
        });
    },
    //修改股票池分组名称/删除股票池分组
    updateStockPoolGroup:function(req, res, next){
        var params = req.body;
        if (params == null) {
            res.redirect('/error');
            return;
        }
        stockpoolDAO.update(params,function(err,result){
            next(err || result);
        });
    },
    //查询股票池分组列表
    listStockPoolGroup:function(req,res,next){
        var params = req.body;
        if (params == null) {
            res.redirect('/error');
            return;
        }
        async.waterfall([
            function(cb){
                stockpoolDAO.list(params,function(err,result){
                    cb(err, result);
                });
            },
            function(result,cb){
                var list = result.obj || [];
                var voList = new Array(list.length);
                if(list.length>0){
                    var finish = 0;
                    for(var i=0;i<list.length;i++){
                        (function(i){
                            stockpoolDAO.list({parentId:list[i].rowId},function(err,$result){
                                var vo = convertVO(list[i]);
                                var $children = $result.obj || [];
                                for(var j=0;j<$children.length;j++){
                                    vo.children.push(convertVO($children[j]));
                                }
                                voList[i] = vo;
                                if(++finish == list.length){
                                    result.obj = voList;
                                    cb(null,result);
                                }
                            });
                        })(i);
                    }
                }else{
                    cb(null,result);
                }
            }
        ],function(err, result){
            next(err || result);
        });

        function convertVO(po){
            return {id:po.rowId,name:po.poolName,parentId:po.parentId,children:[]};
        }
    },
    isStockExistInPool:function (req,res,next) {
        dicStock.getStockByCode(req.params,function (err, result) {
            if (result && result.obj){
                var stock = result.obj;
                stockRecommend.getListByStockId({stockId:stock.rowId,enable:'1',actionType:'stockrecommend',isRecommend:'0'},function (err, result) {
                    var exist = result && result.obj && result.obj.length>0;
                    next({exist:exist});
                });
            }
        });
    }
};
